package edu.hpu.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;


/**
 * @Author 三分恶
 * @Date 2020/7/15
 * @Description 异步式任务
 */
@Component
public class AsyncTask {
   Logger log= LoggerFactory.getLogger(AsyncTask.class);

    private Random random = new Random();

    /**
     * 定义三个异步式方法
     * @throws InterruptedException
     */
    @Async
    public Future<String> taskOne() throws InterruptedException {
        long start = System.currentTimeMillis();
        //随机休眠若干毫秒
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任务一执行完成耗时{}秒", (end - start)/1000f);
        return new AsyncResult<>("任务一完事了");
    }

    @Async
    public Future<String> taskTwo() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任务二执行完成耗时{}秒", (end - start)/1000f);
        return new AsyncResult<>("任务二完事了");
    }

    @Async
    public Future<String> taskThree() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        log.info("任务三执行完成耗时{}秒", (end - start)/1000f);
        return new AsyncResult<>("任务三完事了");
    }

}
